// loading.directive.js
import { createApp } from 'vue';
import LoadingComponent from './index.vue';

const loadingDirective = {
  mounted(el, binding) {
    const app = createApp(LoadingComponent);
    const instance = app.mount(document.createElement('div'));

    el.instance = instance;
    el.loadingElement = instance.$el;

    // 直接将加载元素挂载到当前元素上
    el.appendChild(el.loadingElement);
    el.style.position = 'relative';
    // 设置初始状态
    console.log(binding);
    binding.value ? showLoading(el) : hideLoading(el);
    // 存储原始样式
    el.originalPosition = el.style.position;
    el.originalOverflow = el.style.overflow;
  },

  updated(el, binding) {
    if (binding.value !== binding.oldValue) {
      binding.value ? showLoading(el) : hideLoading(el);
    }
  },

  unmounted(el) {
    hideLoading(el);
    el.instance.$destroy();
    el.instance = null;
    el.loadingElement = null;
  },
};

function showLoading(el) {
  const style = getComputedStyle(el);

  // 如果元素没有定位，添加相对定位
  if (style.position === 'static') {
    el.style.position = 'relative';
  }

  // 防止内容滚动
  el.style.overflow = 'hidden';

  // 显示加载元素
  el.loadingElement.classList.add('show');
}

function hideLoading(el) {
  // 恢复原始样式
  el.style.position = el.originalPosition;
  el.style.overflow = el.originalOverflow;

  // 隐藏加载元素
  el.loadingElement.classList.remove('show');
}

export default loadingDirective;
